<template>
	<view class="search-panel-container">
		<!-- 触发搜索弹窗的按钮（插槽，由父组件自定义） -->
		<view @click="openPopup" class="search-trigger">
			<slot name="trigger"></slot>
		</view>
		
		<!-- 搜索弹窗 -->
		<uni-popup 
			ref="searchPopup" 
			mode="bottom"
			type="bottom"
			:mask="true"
			:animation="true"
			@change="onPopupChange"
		>
			<view class="popup-content">
				<view class="index-search">
					<view class="index-search-left">
						<image src="@/static/img/search.png" mode="aspectFill"></image>
						<!-- 移除v-model绑定父组件的modelValue，改为内部变量 -->
						<input type="text" placeholder="搜索" v-model="internalSearchWord" 
							@confirm="handleSearch" @focus="focus" @blur="blur"/>
						<!-- 新增：输入框清除按钮 -->
						<uni-icons 
							v-if="internalSearchWord"
							type="clear" 
							size="24" 
							@click="clearSearchWord"
							class="clear-icon"
						/>
					</view>
					<view class="cancel-btn" @click="closePopup">
						取消
					</view>
				</view>
				
				<view class="search-history" v-if="internalSearchWord">
					<view class="search-history-head">
						<view>当前搜索关键词</view>
						<image src="@/static/img/delete.png" mode="aspectFit" @click="clearSearchWord"></image>
					</view>
					<view class="search-history-list">
						<view class="item">
							<text>{{internalSearchWord}}</text>
						</view>
					</view>
				</view>
				
				<view class="search-history">
					<view class="search-history-head">
						<view>搜索历史</view>
						<image src="@/static/img/delete.png" mode="aspectFit" @click="clearAllHistory" 
							v-if="searchHistory.length > 0"></image>
					</view>
					<view class="search-history-list" v-if="searchHistory.length > 0">
						<view class="item" 
							v-for="(word,index) in searchHistory" :key="word"> <!-- 用内容作为key更稳定 -->
							<text @click="searchByHistory(word)">{{word}}</text>
							<uni-icons style="margin-left: 5px;" @click.stop="deleteHistoryItem(word)" 
								type="trash" color="#ffffff" size="20"></uni-icons>
						</view>
					</view>
					<view class="empty-history" v-else>
						暂无搜索历史
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>

export default {
	components: {
	},
	props: {
		// searchHistory: {
		// 	type: Array,
		// 	default: () => []
		// },
		maxHistoryCount: { // 新增：允许父组件控制历史记录最大数量
			type: Number,
			default: 50
		}
	},
	data() {
		return {
			// 关键词改为组件内部管理的变量，不再依赖父组件传入
			internalSearchWord: '',
			searchHistory: []
		};
	},
	methods: {
		// 打开弹窗
		openPopup() {
			uni.getStorage({
				key: 'searchHistory',
				success: res => {
					this.searchHistory = res.data;
				}
			})
			this.$refs.searchPopup.open();
			// 优化：打开弹窗时自动聚焦输入框
			this.$nextTick(() => {
				const input = uni.createSelectorQuery().select('.index-search input');
				input.fields({ focus: true }, () => {}).exec();
			});
		},
		// 关闭弹窗
		closePopup() {
			this.$refs.searchPopup.close();
			uni.hideKeyboard();
			// 优化：关闭弹窗时清空输入框（可选，根据需求调整）
			// this.internalSearchWord = '';
		},
		// 弹窗状态变化
		onPopupChange(isOpen) {
			this.$emit('popup-change', isOpen); // 始终触发，方便父组件处理
		},
		focus() {
			this.$emit('focus');
			if (uni.getSystemInfoSync().platform === 'ios') {
			    this.$nextTick(() => {
			      uni.createSelectorQuery()
			          .in(this)
			          .select('.popup-content')
			          .fields({
			            scrollHeight: true, // 需要总高度
			            node: true // 同时获取节点实例
			          }, data => {
			            if (data && data.node) {
			              data.node.scrollTop = data.scrollHeight; // 直接设置滚动位置
			            }
			          })
			          .exec();
			    });
			}
		},
		blur() {
			setTimeout(() => {
				this.$emit('blur');
			}, 200);
		},
		// 处理搜索
		handleSearch() {
			const keyword = this.internalSearchWord.trim();
			if (!keyword) return;
			// 添加到历史记录
			this.addToHistory(keyword);
			// 向父组件传递搜索关键词
			this.$emit('search', keyword);
			// 搜索后可选择清空输入框
			// this.internalSearchWord = '';
		},
		// 清除所有历史记录
		clearAllHistory() {
			uni.removeStorage({
				key: 'searchHistory',
				success: (res) => {
					this.searchHistory = [];
				}
			})
		},
		// 清除查询的筛选
		clearSearchWord() {
			// console.log("清除关键词")
			this.internalSearchWord = ''
			this.$emit('search', '');
		},
		// 删除单个历史记录（优化：不依赖索引，避免数组错乱）
		deleteHistoryItem(word) {
			const newHistory = this.searchHistory.filter(item => item !== word);
			this.searchHistory = newHistory
			uni.setStorage({
				key: 'searchHistory',
				data: this.searchHistory
			})
		},
		// 从历史记录搜索
		searchByHistory(word) {
			this.internalSearchWord = word;
			this.handleSearch();
		},
		// 清除输入框内容
		// clearSearchWord() {
		// 	this.internalSearchWord = '';
		// },
		// 添加到历史记录（去重+限制数量）
		addToHistory(word) {
			// 去重并添加到头部
			const newHistory = [word, ...this.searchHistory.filter(item => item !== word)]
				.slice(0, this.maxHistoryCount); // 限制最大数量
			this.searchHistory = newHistory
			uni.setStorage({
				key: 'searchHistory',
				data: this.searchHistory
			})
		}
	}
}
</script>
<style scoped lang="scss">
.search-trigger {
	/* 触发按钮容器样式，由父组件通过slot内容自定义 */
}

.index-search {
	padding: 16rpx;
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: space-between;
	margin: 40rpx 30rpx 30rpx 30rpx;
	background-color: #f7f7f7;
	border-radius: 50rpx;
	box-sizing: border-box;

	image {
		width: 26rpx;
		height: 26rpx;
		margin-left: 20rpx;
		margin-right: 20rpx;
	}

	.index-search-left {
		display: flex;
		justify-content: space-around;
		align-items: center;
		position: relative;
		flex: 1;

		input {
			position: relative;
			z-index: 2;
			background: transparent;
			color: #000000;
			flex: 1;
			height: 100%;
			font-size: 28rpx;
			padding: 0;
		}
		
		.clear-icon {
			position: absolute;
			right: 20rpx;
			color: #999;
			z-index: 3;
			cursor: pointer;
		}
	}

	.cancel-btn {
		font-size: 28rpx;
		color: #007aff;
		padding: 0 20rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
}

.search-history {
	padding: 0 30rpx;
	margin-bottom: env(safe-area-inset-bottom);

	.search-history-head {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 80rpx;
		border-bottom: 1px solid #eee;

		view {
			font-size: 28rpx;
			color: #666;
		}

		image {
			width: 30rpx;
			height: 30rpx;
		}
	}

	.search-history-list {
		display: flex;
		flex-wrap: wrap;
		padding: 20rpx 0;
		max-height: calc(100vh - 300rpx);
		overflow-y: auto;

		.item {
			display: flex;
			align-items: center;
			padding: 10rpx 20rpx;
			margin: 0 15rpx 15rpx 0;
			border-radius: 30rpx;
			border: 1px solid #009688;
			background-color: #009688;
			color: #fff;
			font-size: 26rpx;
		}
	}

	.empty-history {
		height: 200rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #999;
		font-size: 28rpx;
	}
}

.popup-content {
	width: 100vw;
	height: 60vh;
	max-height: 80vh; /* 移除固定最大高度限制 */
	background-color: #fff;
	border-top-left-radius: 20rpx;
	border-top-right-radius: 20rpx;
	overflow-y: auto;
	padding-bottom: env(safe-area-inset-bottom);
	box-sizing: border-box; /* 确保padding不影响整体高度 */
}
// .uni-popup {
//   /* 确保弹窗从底部平滑弹出 */
//   transform: translate3d(0, 100%, 0);
//   transition: transform 0.3s cubic-bezier(0.36, 0.66, 0.04, 1);
// }

.uni-popup--bottom.uni-popup--visible {
  transform: translate3d(0, 0, 0);
}
</style>